package com.socialcoco.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.socialcoco.entity.Grade;
import com.socialcoco.entity.Reward;
import com.socialcoco.exception.myExection;
import com.socialcoco.respone.BaseResponse;
import com.socialcoco.respone.ResultUtils;
import com.socialcoco.respone.resultenum;
import com.socialcoco.serviceImpl.GradeServiceImpl;
import com.socialcoco.serviceImpl.RewardServiceImpl;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *       用户抽奖获取奖品
 * </p>
 *
 * @author 赵志浩
 * @since 2022-04-22 10:41:37
 */
@Slf4j
@RestController
@RequestMapping("/socialcoco/user")
public class RewardController {
    @Autowired
    private RewardServiceImpl rewardService;
    @Autowired
    private GradeServiceImpl gradeService;

    @ApiOperation("用户抽奖")
    @PostMapping("/reward")
    public BaseResponse<Object> reward(@RequestBody Reward reward){
        if(reward==null){
            throw new myExection(resultenum.BODY_NULL.getCode(),resultenum.BODY_NULL.getMsg());
        }
        //查找出用户，并且添加奖品
        QueryWrapper<Grade> gradeQueryWrapper=new QueryWrapper<>();
        gradeQueryWrapper.eq("uid",reward.getUid());
        Grade one = gradeService.getOne(gradeQueryWrapper);
        one.setFraction(one.getFraction()-10);
        if(reward.getRewarditem().contains("积分")){
            String s=reward.getRewarditem().substring(0,reward.getRewarditem().indexOf('积'));
            one.setFraction(one.getFraction()+Integer.valueOf(s));
        }
        boolean b = gradeService.updateById(one);
        if(b){
            reward.setCreateTime(new Date());
            rewardService.save(reward);
        }
        return ResultUtils.success("rewardOK");
    }
    @ApiOperation("查看用户奖品")
    @GetMapping("/listReward/{uid}")
    public BaseResponse<Object> listReward(@PathVariable String uid){
        HashMap<Object, Object> HashMap = new HashMap<>();
        //查找奖品
        QueryWrapper<Reward> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        List<Reward> list = rewardService.list(queryWrapper);
        //查找用户积分
        QueryWrapper<Grade> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("uid",uid);
        Grade one = gradeService.getOne(queryWrapper1);
        //把这两个信息写入map并且返回
        HashMap.put("user",one);
        HashMap.put("list",list);
        return  ResultUtils.success(HashMap);
    }
}

